package com.hisan.freeride.common.base;


import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;


import com.blankj.utilcode.util.LogUtils;
import com.google.gson.internal.LinkedTreeMap;
import com.hisan.freeride.R;
import com.hisan.freeride.common.model.ErrorModel;
import com.hisan.freeride.common.service.NetBroadcastReceiver;
import com.hisan.freeride.common.service.NetEvent;
import com.hisan.freeride.common.state.EmptyState;
import com.hisan.freeride.common.state.StateModel;
import com.hisan.freeride.common.utils.ActivityEffectUtil;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.utils.GsonUtils;
import com.hisan.freeride.common.view.AlertDialog;
import com.hisan.freeride.common.view.OnClickListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import es.dmoral.toasty.Toasty;


/**
 * 创建时间 : 2017/7/13
 * 创建人：yangyingqi
 * 公司：嘉善和盛网络有限公司
 * 备注：Activity基类 ---协同stateModel处理error及重新加载操作
 */
public abstract class BaseActivity<VB extends ViewDataBinding> extends AppCompatActivity implements StateModel.CallBack,OnClickListener, NetEvent {
    protected VB mBinding;
    public AppManager appManger;
    protected StateModel mStateModel;
    private boolean isok=true;
    public AlertDialog mDialog;
    private AlertDialog.Builder builder;
    /**
     * 监控网络的广播
     */
    private NetBroadcastReceiver netBroadcastReceiver;
    private int netMobile;

    @Override
    public void onStart() {
        super.onStart();
        //注册广播
        if (netBroadcastReceiver == null) {
            netBroadcastReceiver = new NetBroadcastReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(netBroadcastReceiver, filter);
            /**
             * 设置监听
             */
            netBroadcastReceiver.setNetEvent(this);
        }
    }
    public AlertDialog getmDialog(String msg,String cancel,String ok) {
        builder = new AlertDialog.Builder(this);
        builder.setMessage(msg)
                .setTopImage(R.mipmap.certification_prompt)
                .setNegativeButton(cancel, (dialog, which) ->   onCancel())
                .setPositiveButton(ok, (dialog, which) -> {
                    onCancel();
                    onOk();
                });
        mDialog = builder.create();
        return mDialog;
    }

    @Override
    public void onNetChange(int netMobile) {
        this.netMobile = netMobile;
        isNetConnect();
    }

    @Override
    public void onOk() {

    }

    @Override
    public void onCancel() {
        if (builder.getNegativeButtonText().equals("取消")){
            if (mDialog!=null&&mDialog.isShowing())mDialog.dismiss();
        }
    }

    private void isNetConnect() {
        switch (netMobile) {
            case -1://没有网络
                mStateModel.setEmptyState(EmptyState.NET_ERROR);
                break;
        }
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //解决软键盘将底部按钮顶上去
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        appManger = AppManager.getInstance();
        appManger.addActivity(this);
        if (savedInstanceState != null) {
            BaseAppLication.getInstance().restartApplication();
            String FRAGMENTS_TAG = "android:support:fragments";
            savedInstanceState.remove(FRAGMENTS_TAG);
        }
        mStateModel = new StateModel();
        mStateModel.attach(this);

        //竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mBinding = DataBindingUtil.setContentView(this, getLayoutId());
        initView();//初始化view
        initEvent();//处理事件
        loadData(true);//加载数据

    }
    //返回布局
    protected abstract int getLayoutId();
    protected abstract void initView();
    protected abstract void initEvent();
    protected abstract void loadData(boolean isRefresh);

    //正常弹窗
    public void showToast(String msg){
        Toasty.warning(this,msg, Toast.LENGTH_LONG).show();
    }
    //成功弹窗
    public void showSuccessToast(String msg){
        Toasty.warning(this,msg, Toast.LENGTH_LONG).show();
       // Toasty.info(this,msg, Toast.LENGTH_LONG).show();
    }
    //失败弹窗
    public void shoewErrorToast(String msg){
        Toasty.warning(this,msg, Toast.LENGTH_LONG).show();
    }
    @Override
    public void onFailure(Throwable e) {
        LogUtils.v("xxx",e);
    }

    @Override
    public void onReload() {
        loadData(true);
    }
    //关闭
    public  void finishActivity(boolean isboolean){
        // 结束Activity&从堆栈中移除
        appManger.finishActivity(this,isboolean);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mStateModel != null) {
            mStateModel.detach();
        }
        OkGo.getInstance().cancelTag(this);
        if (netBroadcastReceiver != null) {
            //注销广播
            unregisterReceiver(netBroadcastReceiver);
        }
    }
    /**
     * startActivityForResult 跳转
     */
    public void startActivityForResult(Class<? extends AppCompatActivity> activity, int requestCode, Bundle bundle,boolean isboolean ) {
        Intent intent = new Intent();
        intent.setClass(this, activity);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
        if (isboolean){
            ActivityEffectUtil.setActivityEffect(this, ActivityEffectUtil.ENTER_RIGHT_TO_LEFT);
        }else{
            ActivityEffectUtil.setActivityEffect(this, ActivityEffectUtil.ENTER_BOTTOM_TO_TOP);
        }
    }

    //显示错误信息弹窗
    public void showError(Response<Object> response){
        if (!CollectionUtils.isNullOrEmpty(response.getRawResponse())) {
            try {
                if (response.code()<=400){
                    LinkedTreeMap<String,Object> maps= (LinkedTreeMap<String, Object>) response.body();
                    if (!CollectionUtils.isNullOrEmpty(maps)){
                        shoewErrorToast(maps.get("msg").toString());
                    }
                }else {
                    ErrorModel errorModel=  GsonUtils.GsonToBean(response.getRawResponse().body().string(),ErrorModel.class);
                    if (!CollectionUtils.isNullOrEmpty(errorModel)){
                        shoewErrorToast(errorModel.getMsg());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public boolean isOk(Response response){
        return isok ? response.code() >= 200 && response.code() < 300:response.code()>300;
    }
    public boolean isNull(Response response){
        return isok ? response.code() == 200 : response.code() >=203;
    }


    //显示错误信息显示不同错误布局
    public void showErrorView(int code){
        if (code==-1){
            mStateModel.setEmptyState(EmptyState.NET_ERROR);
        }else {
            mStateModel.setEmptyState(EmptyState.NOT_AVAILABLE);
        }
    }
    public void noData(){
        mStateModel.setEmptyState(EmptyState.EMPTY);
    }
    public void showData(){
        mStateModel.setEmptyState(EmptyState.NORMAL);
    }
    //下面的方法作用：只要点击的区域不是EditText已经弹出的软键盘就会消失
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
    @Override
    protected synchronized void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        appManger.finishAllActivity();
        android.os.Process.killProcess(android.os.Process.myPid());//杀掉App中的所有进程
        BaseAppLication.getInstance().restartApplication();
    }
}
